import React, { useEffect, useRef, useState } from 'react';
import { Button, Drawer, Input, Space, Table, Tooltip } from 'antd';
import { CodeSandboxOutlined } from '@ant-design/icons';
import type { TableProps } from 'antd';
import { fetchExtractTables } from '@/service/api';
import type { DatasetCreatorRef } from './dataset-creator';
import DatasetCreator from './dataset-creator';
const { Search } = Input;

interface TableListProps {
  database: Bn.Meta.MetaDatabase | undefined;
}

const TableList = ({ database }: TableListProps) => {
  const tables = useRef<Bn.Meta.MetaTable[]>([]);
  const creatorRef = useRef<DatasetCreatorRef>(null);
  const [data, setData] = useState<Bn.Meta.MetaTable[]>();
  const [searchText, setSearchText] = useState<string>('');
  const [currentTable, setCurrentTable] = useState<Bn.Meta.MetaTable>();
  const [open, setOpen] = useState(false);

  const handleNewTableButtonClick = (record: Bn.Meta.MetaTable) => {
    console.log('TableList::handleNewTableButtonClick', record);
    setOpen(true);
    setCurrentTable(record);
  };

  const columns: TableProps<Bn.Meta.MetaTable>['columns'] = [
    {
      title: '架构名称',
      dataIndex: 'tableSchema',
      key: 'tableSchema',
      width: 150
    },
    {
      title: '表名',
      dataIndex: 'tableName',
      key: 'tableName',
      width: '85%'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Tooltip title="新建数据集">
            <Button
              color="primary"
              variant="text"
              onClick={() => handleNewTableButtonClick(record)}
              icon={<CodeSandboxOutlined />}
            />
          </Tooltip>
        </Space>
      )
    }
  ];

  useEffect(() => {
    (async () => {
      if (database?.dbName) {
        const _tables = (await fetchExtractTables(database?.dbName)).data;
        if (_tables) {
          tables.current = _tables;
        }
        setData(tables.current);
      }
    })();
  }, [database]);

  const onSearch = (value: string) => {
    if (value.trim() === '') {
      // 空文本展示所有数据
      setData(tables.current);
      return;
    }
    const searchResults = [] as Bn.Meta.MetaTable[];
    tables.current.forEach(ele => {
      if (ele.tableName.toLowerCase().includes(value.toLowerCase())) {
        searchResults.push(ele);
      }
    });
    setData(searchResults);
  };

  const handleClick = async () => {
    if (creatorRef.current) {
      await creatorRef.current.save();
    }
  };

  return (
    <Space direction="vertical">
      <Search
        value={searchText}
        style={{ width: 350 }}
        placeholder="请输入查询内容"
        allowClear
        onSearch={onSearch}
        onChange={e => {
          setSearchText(e.target.value);
        }}
        onPressEnter={() => {
          onSearch(searchText);
        }}
      ></Search>
      <Table<Bn.Meta.MetaTable>
        size="small"
        rowKey={'id'}
        pagination={false}
        columns={columns}
        dataSource={data}
        scroll={{ y: document.body.clientHeight - 316 }}
      />
      <Drawer
        title="新建数据集"
        placement={'right'}
        size="large"
        closable={true}
        onClose={() => setOpen(false)}
        open={open}
        key="new_table_drawer"
        extra={
          <Space>
            <Button
              onClick={handleClick}
              type="primary"
            >
              新建数据集
            </Button>
          </Space>
        }
      >
        <DatasetCreator
          ref={creatorRef}
          table={currentTable}
          close={() => setOpen(false)}
        ></DatasetCreator>
      </Drawer>
    </Space>
  );
};

export default TableList;
